<!--
  * 退款表
  *
  * @Author:    zhoujk
  * @Date:      2025-02-13 14:47:34
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="退款日期" class="smart-query-form-item">
        <a-range-picker :allowClear="true" :inputReadOnly="true" v-model:value="queryForm.fTime" style="width: 250px" @change="onChangeTTime" />
      </a-form-item>
      <a-form-item label="退款订单号" class="smart-query-form-item">
        <a-select
          style="width: 80px"
          v-model:value="queryForm.orderField"
          :options="ORDER_FIELD_REFUND"
          :dropdown-match-select-width="false"
          placeholder="请选择"
          @change="onChangeOrderField"
        />
        <a-input style="width: 200px" v-model:value="queryForm[queryForm.orderField]" placeholder="退款订单号" />
      </a-form-item>
      <a-form-item label="订单号" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.orderId" placeholder="订单号" />
      </a-form-item>
      <a-form-item label="商户名称" class="smart-query-form-item">
        <CustomSelect
          style="width: 200px"
          v-model:value="queryForm.merchantId"
          :placeholder="'请选择'"
          :api="merchantApi.page"
          :queryParams="merchantParams"
          queryParamKey="companyNameLeftLike"
          valueField="id"
          labelField="companyName,no"
        />
      </a-form-item>
      <a-form-item label="通道类型" class="smart-query-form-item">
        <SmartEnumSelect v-model:value="queryForm.channelType" enumName="ZZB_CHANNEL_TYPE_ENUM" placeholder="请选择通道类型" />
      </a-form-item>
      <!-- <a-form-item label="支付通道" class="smart-query-form-item">
        <CustomSelect
          v-model:value="queryForm.channelId"
          :placeholder="'请选择支付通道'"
          :api="channelApi.queryPage"
          value-field="id"
          label-field="channelName"
        />
      </a-form-item> -->
      <a-form-item label="退款状态" class="smart-query-form-item">
        <a-select
          v-model:value="queryForm.status"
          :dropdown-match-select-width="false"
          allowClear
          :options="REFUND_TYPE"
          placeholder="请选择退款状态"
        />
      </a-form-item>
      <a-form-item label="所属代理" class="smart-query-form-item">
        <CustomSelect
          v-model:value="queryForm.agentId"
          :placeholder="'请选择所属代理'"
          :api="agentApi.page"
          queryParamKey="companyNameLeftLike"
          value-field="id"
          label-field="companyName,no"
        />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block"></div>
      <div class="smart-table-setting-block">
        <!-- <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.OPERATION.REFUND" :refresh="queryData" /> -->
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table
      size="small"
      :dataSource="tableData"
      :columns="columns"
      rowKey="id"
      bordered
      :loading="tableLoading"
      :pagination="false"
      :scroll="{ x: 'max-content' }"
    >
      <template #bodyCell="{ column }">
        <template v-if="column.dataIndex === 'action'">
          <a-button @click="showDetail(record)" type="link">详情</a-button>
        </template>
      </template>
    </a-table>
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>
</template>
<script setup>
  import { reactive, ref, onMounted, getCurrentInstance, h, watch } from 'vue'
  import { message, Tag } from 'ant-design-vue'
  import { refundApi } from '/@/api/business/b-operation/refund/refund-api'
  import { channelApi } from '/@/api/business/b-operation/channel/channel-api'
  import { agentApi } from '/@/api/business/b-operation/agent/agent-api'
  import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import TableOperator from '/@/components/support/table-operator/index.vue'
  import DictSelect from '/@/components/business/comment/DataDictionariesSelect.vue'
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue'
  import dayjs from 'dayjs'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { ZZB_ENABLE_STATUS_ENUM } from '/@/constants/system/system-const.js'
  import { merchantApi } from '/@/api/business/b-operation/merchant/merchant-api.js'
  import { TABLE_ID_CONST } from '/@/constants/support/table-id-const.js'
  import { formatToMoney, selectDictLabel } from '/@/utils/common'
  import {
    ORDER_TYPE, //订单类型
    REFUND_TYPE, //退款状态
    ORDER_FIELD_REFUND, //订单号对应字段
    ZZB_PAY_WAY,
  } from '/@/constants/dict'
  import { useRouter, useRoute } from 'vue-router'

  const route = useRoute()
  const { proxy } = getCurrentInstance()

  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '退款订单号',
      dataIndex: 'refundOrder',
      width: 300,
      customRender: (column) => {
        let { id, oId, tId } = column.record
        let mText = id ? h('div', { style: { paddingBottom: '10px' } }, [h(Tag, { color: '#2db7f5' }, '交易'), id]) : ''
        let oText = oId ? h('div', { style: { paddingBottom: '10px' } }, [h(Tag, { color: 'orange' }, '支付'), oId]) : ''
        let tText = tId ? h('div', [h(Tag, { color: 'cyan' }, '渠道'), tId]) : ''

        return h('div', [mText, oText, tText])
      },
      ellipsis: true,
    },
    {
      title: '订单号',
      dataIndex: 'orderId',
      ellipsis: true,
    },
    {
      title: '交易余额',
      dataIndex: 'orderBalance',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '退款金额',
      dataIndex: 'refundAmt',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '手续费退还金额',
      dataIndex: 'fee',
      customRender: (column) => formatToMoney(column.text / 100),
      ellipsis: true,
    },
    {
      title: '退款状态',
      dataIndex: 'status',
      customRender: ({ text }) => {
        return selectDictLabel(REFUND_TYPE, text)
      },
      ellipsis: true,
    },
    {
      title: '所属代理',
      dataIndex: 'oAgentName',
      ellipsis: true,
    },
    {
      title: '商户名称',
      dataIndex: 'merchantName',
      ellipsis: true,
    },
    {
      title: '业务类型',
      dataIndex: 'orderType',
      customRender: ({ text }) => {
        return selectDictLabel(ORDER_TYPE, text)
      },
      ellipsis: true,
    },
    {
      title: '通道名称',
      dataIndex: 'channelName',
      // customRender: (data) => {
      //   return proxy.$smartEnumPlugin.getDescByValue('ZZB_CHANNEL_TYPE_ENUM', data?.channelType)
      // },
      ellipsis: true,
    },
    {
      title: '交易类型',
      dataIndex: 'payType',
      customRender: ({ text }) => proxy.$smartEnumPlugin.getDescByValue('ZZB_PAY_TYPE_ENUM', text),
      ellipsis: true,
    },
    {
      title: '支付方式',
      dataIndex: 'payWay',
      customRender: ({ text }) => selectDictLabel(ZZB_PAY_WAY, text),
      ellipsis: true,
    },
    {
      title: '退款原因',
      dataIndex: 'reason',
      ellipsis: true,
    },
    {
      title: '退款失败原因',
      dataIndex: 'failMsg',
      ellipsis: true,
    },
    {
      title: '退款时间',
      dataIndex: 'fTime',
      customRender: (column) => dayjs(column.text).format('YYYY-MM-DD HH:mm:ss'),
      width: 180,
      ellipsis: true,
    },
    // {
    //   title: '操作',
    //   dataIndex: 'action',
    //   ellipsis: true,
    // },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    fTime: [dayjs().startOf('day'), dayjs().endOf('day')],
    fTimeBegin: dayjs().startOf('day').valueOf(), //前一天
    fTimeEnd: dayjs().endOf('day').valueOf(), //前一天
    orderField: 'keyWord',
    keyWord: undefined, //全部
    mId: undefined, //交易订单号（系统生成的订单号）
    oId: undefined, //支付订单号（支付宝/微信返回的订单号）
    tId: undefined, //渠道订单号（间连返回的订单编号）
    orderId: undefined, //交易订单号
    merchantId: undefined, //商户名称
    channelType: undefined, //通道类型
    status: undefined, //退款状态
    agentId: undefined, //代理商
    id: undefined, //退款订单号
    storeName: undefined, //门店名称
    channelId: undefined, //支付通道
    payType: undefined, //交易类型
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    try {
      const payload = { ...queryForm }
      delete payload.tTime
      let queryResult = await refundApi.page(payload)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  function onChangeDay(flag) {
    if (flag) {
      queryForm.fTime = dayjs(queryForm.fTime).subtract(1, 'days')
    } else {
      queryForm.fTime = dayjs(queryForm.fTime).add(1, 'days')
    }
    onChangeTTime(queryForm.fTime)
  }

  function onChangeTTime(dates) {
    queryForm.fTimeBegin = dates ? dayjs(dates[0]).startOf('day').valueOf() : undefined
    queryForm.fTimeEnd = dates ? dayjs(dates[1]).endOf('day').valueOf() : undefined
  }

  const merchantParams = reactive({
    showRoleFlag: false,
  })

  function showDetail(rowData) {}
  // ----------------- 配置信息操作 -----------------
  function copy(content) {
    // 创建元素用于复制
    const aux = document.createElement('input')
    // 设置元素内容
    aux.setAttribute('value', content)
    // 将元素插入页面进行调用
    document.body.appendChild(aux)
    // 复制内容
    aux.select()
    // 将内容复制到剪贴板
    document.execCommand('copy')
    // 删除创建元素
    document.body.removeChild(aux)

    message.success('复制成功')
  }

  // 切换订单号选择
  watch(
    () => queryForm.orderField,
    (val, oldVal) => {
      if (val) {
        queryForm[oldVal] = undefined
      }
    },
  )

  watch(
    () => route.query,
    (val) => {
      if (val?.id) {
        queryForm.orderId = val.id
        queryForm.fTime = undefined
        queryForm.fTimeBegin = undefined
        queryForm.fTimeEnd = undefined
        queryData()
      }
    },
    { deep: true, immediate: true },
  )

  onMounted(queryData)
</script>
